<?php
//error_reporting(0);
require("../../database.php");
$mail_conf=require("../../mail.config.php");
require_once('../../imap/ImapMailbox.php');
// IMAP must be enabled in Google Mail Settings
define('GMAIL_EMAIL',$mail_conf['username']);
define('GMAIL_PASSWORD', $mail_conf['password']);
define('ATTACHMENTS_DIR', '../../imap/example/attachments');
//define('ATTACHMENTS_DIR', dirname(__FILE__) . '/attachments');

//$mailbox = new ImapMailbox('{imap.gmail.com:993/imap/ssl}INBOX', GMAIL_EMAIL, GMAIL_PASSWORD, ATTACHMENTS_DIR, 'utf-8');
$mailbox = new ImapMailbox($mail_conf['imap_host'], GMAIL_EMAIL, GMAIL_PASSWORD, ATTACHMENTS_DIR, 'utf-8');

$mails = array();
require_once("../../phpmailer/class.phpmailer.php");
$mail_php = new PHPMailer();
$marray=array();
$marray=$mailbox->searchMails('ALL');

foreach($marray as $mailId) {
	$mail = $mailbox->getMail($mailId);
	$mails[] = $mail;
	$mailbox->setMailAsSeen($mail->mId);
	$mailbox->deleteMail($mail->mId);
}
if(!empty($mails)){
	foreach($mails as $v){
		$email=$v->fromAddress;
		$message=$v->textPlain;
		$message=explode(":: Reply above this line to post a reply ::",$message);
		$message=trim($message[0]);
		$message=preg_replace("/>\s*\*\*/",'',$message);
		$message=htmlentities($message,ENT_QUOTES,'UTF-8');
		$message=nl2br(trim($message));
		$tmp=$v->subject;
		$tmp2=explode("<ID:",$tmp);
		$r_num=substr($tmp2[1],0,-1);
		$attaches=$v->attachments;
		if(!empty($attaches)){
		$atta='<div style="border-top:1px dashed #ddd;height:2px;"></div><ul class="file-icons">';
		foreach($attaches as $m=>$n){
			$m_tmp=substr($m,strrpos($m,".")+1);
			if(in_array($m_tmp,array('jpg','JPG','gif','GIF','png','PNG','bmp','BMP'))){
				$m_tmp="img";
			}
			if(!is_dir("../../imap/example/attachments/".$r_num)){
				mkdir("../../imap/example/attachments/".$r_num, 0777);
			}
			rename("../../imap/example/attachments/".$m,"../../imap/example/attachments/".$r_num."/".$m);
			$atta.="<li class='".$m_tmp."'><a target='_blank' href='./imap/example/attachments/".$r_num."/".$m."'>".$m."</a></li>";
		}
		$atta.='</ul>';
	}else{
		$atta='';
	}
	$tmp_sql="select * from `cms_advertiser_pmb` where t_num='".$r_num."'";
	$tmp_query=mysql_query($tmp_sql);
	$tmp_num=mysql_num_rows($tmp_query);
	if($tmp_num>0){
		$tmp_arr_arr=mysql_fetch_array($tmp_query);
	}
	
	$tmp_sql="select * from `cms_user_pmb` where t_num='".$r_num."'";
	$tmp_num=mysql_num_rows(mysql_query($tmp_sql));
	if($tmp_num<=0 && ($email!=$tmp_arr_arr['email']) ){
		$sql_tmp_2="select * from cms_advertiser_pmb where t_num='".$r_num."'";
		$arr_tmp_2=mysql_fetch_array(mysql_query($sql_tmp_2));
    $cnum_sql_2="select * from `cms_accounts` where email='".$arr_tmp_2['email']."'";
    $cnum_arr_2=mysql_fetch_array(mysql_query($cnum_sql_2));
    
  	$sql="insert into cms_advertiser_pmb(createdDate,message_read,email,message,r_num) values('".time()."',0,'".$email."','".addslashes($message.$atta)."','".$r_num."')";
    mysql_query($sql);
    $sql_tmp_1="select * from cms_advertiser_pmb where r_num='".$r_num."'";
		$arr_tmp_1=mysql_fetch_array(mysql_query($sql_tmp_1));
    $cnum_sql="select * from `cms_accounts` where email='".$arr_tmp_1['email']."'";
    $cnum_arr=mysql_fetch_array(mysql_query($cnum_sql));
    $createdByUserNum_copy=$cnum_arr_2['num'];
    $updatedByUserNum_copy=$cnum_arr_2['num'];
    $email_copy=$cnum_arr['email'];
    $phone_copy=$cnum_arr['telephone_number'];
    $message_copy=nl2br(addslashes($message.$atta));
    $first_name_copy=$cnum_arr['first_name'];
    $last_name_copy=$cnum_arr['last_name'];
    $organisation_copy=$cnum_arr['organisation_name'];
    $subject_copy=$arr_tmp_2['subject'];
    
   mysql_query("INSERT INTO `cms_user_pmb` SET             
                      createdDate               = '".time()."',
                      updatedDate               = '".time()."',
                      createdByUserNum          = '".$createdByUserNum_copy."',
                      updatedByUserNum          = '".$updatedByUserNum_copy."',
                      message_read				='0',
                      email						='".$email_copy."',
                      phone						='".$phone_copy."',
                      message					='".$message_copy."',
                      first_name				='".$first_name_copy."',
                      last_name					='".$last_name_copy."',
                      organisation				='".$organisation_copy."',
                      subject           		='".$subject_copy."',
                      t_num						='".$r_num."'"
		      )
      or die("MySQL Error Creating Record:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
if($tmp){
	$subject = $tmp;
	$body = $message;
	$mail_php->ClearAllRecipients();
	$mail_php->CharSet = "UTF-8"; 
	$mail_php->IsSMTP();              
	$mail_php->IsHTML(true);
	$mail_php->SMTPAuth   = true;                  
	//$mail_php->Port       = 587;      //587,465
	//$mail_php->SMTPSecure = 'tls'; //ssl tls
	$mail_php->Host       = $mail_conf['smtp_host'];
	$mail_php->Username   = $mail_conf['username'];
	$mail_php->Password   = $mail_conf['password'];
	$mail_php->From= $mail_conf['from'];
	$mail_php->FromName =$mail_conf['fromname'];
	$mail_php->AddAddress($arr_tmp_2['email']);
	$mail_php->Subject = $subject;
if(!empty($attaches)){
	foreach($attaches as $m=>$n){
		$mail_php->AddAttachment("../../imap/example/attachments/".$r_num."/".$m);
	}
}
	$mail_php->Body=":: Reply above this line to post a reply ::<br><hr>" .$body;
	if(!$mail_php->Send()) {
	  echo "Mailer Error: " . $mail_php->ErrorInfo;
	}
}
    }
    else{
	    	$sql="insert into cms_advertiser_pmb(createdDate,message_read,email,message,r_num) values('".time()."',0,'".$email."','".addslashes($message.$atta)."','".$r_num."')";
				mysql_query($sql);
				$sql_tmp="select * from cms_advertiser_pmb where t_num='".$r_num."'";
				$arr_tmp=mysql_fetch_array(mysql_query($sql_tmp));
				$email_tmp=$arr_tmp['email'];
				if($email_tmp==$email){
					$sql="update cms_advertiser_pmb set message_read=0 where t_num='".$r_num."'";
					mysql_query($sql);
					$sql="update cms_user_pmb set updatedByUserNum=0 where t_num='".$r_num."'";
				mysql_query($sql);
				}else{
					$sql="update cms_user_pmb set message_read=0 where t_num='".$r_num."'";
					mysql_query($sql);
					$sql="update cms_user_pmb set updatedByUserNum=1 where t_num='".$r_num."'";
				mysql_query($sql);
				}		
			
if($tmp){
	$subject = $tmp;
	$body = $message;
	$mail_php->ClearAllRecipients();
	$mail_php->CharSet = "UTF-8"; 
	$mail_php->IsSMTP();
	$mail_php->IsHTML(true);            
	$mail_php->SMTPAuth   = true;                  
	//$mail_php->Port       = 587;      //587,465
	//$mail_php->SMTPSecure = 'tls'; //ssl tls
	$mail_php->Host       = $mail_conf['smtp_host'];
	$mail_php->Username   = $mail_conf['username'];
	$mail_php->Password   = $mail_conf['password'];
	$mail_php->From= $mail_conf['from'];
	$mail_php->FromName =$mail_conf['fromname'];
	if($email_tmp==$email){
		$sql="select * from cms_advertiser_pmb where t_num=".$r_num;
		$arr=mysql_fetch_array(mysql_query($sql));
		$sql="select * from cms_accounts where num=".$arr['createdByUserNum'];
		$arr=mysql_fetch_array(mysql_query($sql));
		$mail_php->AddAddress($arr['email']);
	}else{
		$mail_php->AddAddress($email_tmp);
	}
	$mail_php->Subject = $subject;
if(!empty($attaches)){
	foreach($attaches as $m=>$n){
		$mail_php->AddAttachment("../../imap/example/attachments/".$r_num."/".$m);
	}
}
	$mail_php->Body=":: Reply above this line to post a reply ::<br><hr>" .$body;
	if(!$mail_php->Send()) {
	  echo "Mailer Error: " . $mail_php->ErrorInfo;
	}
}			

    }
	}
}
echo 'ok';
?>